#include "clientwidget.h"
#include "ui_clientwidget.h"
#include <QMessageBox>
ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    ui->setupUi(this);
    ui->progressBar->setValue(0);
    isStart =true;
    tcpSocket = new QTcpSocket(this);
    this->setWindowTitle("客户端");
    connect(tcpSocket,&QTcpSocket::readyRead,[=](){
        //取出接收的内容
        QByteArray buf = tcpSocket->readAll();
        if(isStart)
        {
            isStart =false;
            //解析头部信息 初始化
            fileName = QString(buf).section("##",0,0);
            fileSize = QString(buf).section("##",1,1).toInt();
            //设置进度条最大值
            ui->progressBar->setMaximum(fileSize/1024);
            recvSize =0;
            //打开文件
            info << fileName;
            //弹框提示另存为
            file.setFileName("D:\\"+fileName);
            bool isOk = file.open(QIODevice::WriteOnly);
            if(!isOk)
            {
               info << "写文件出错";
            }
        }
        else
        {
            //文件信息
            qint64 len =file.write(buf);
            recvSize += len;
            ui->progressBar->setValue(recvSize/1024);
            if(recvSize == fileSize)
            {
                file.close();
                QMessageBox::information(this,"接收","接收完毕");
                tcpSocket->disconnectFromHost();
                tcpSocket->close();
            }

        }

    });
}

ClientWidget::~ClientWidget()
{
    delete ui;
}

void ClientWidget::on_buttonConnect_clicked()
{
    //获取服务器的端口和IP
    QString IP = ui->lineEditIP->text();
    qint16 Port = ui->lineEditPort->text().toInt();
    tcpSocket->connectToHost(QHostAddress(IP),Port);
}
